package com.dzsw.javabase.regx.sqllike;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LikeExtractor1 {
    // 正则表达式：捕获列名、LIKE参数、ESCAPE转义符（可选）
    private static final String REGEX =
            "(?i)(`[^`]+`|[\\w.]+)\\s+LIKE\\s+(\\?|'[^']*'|\"[^\"]*\"|#\\{[^}]*\\})(?:\\s+ESCAPE\\s+['\"]([^'\"]*)['\"])?";

    public static List<Map<String, String>> extractLikeConditions(String sql) {
        List<Map<String, String>> results = new ArrayList<>();
        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(sql);

        while (matcher.find()) {
            Map<String, String> condition = new HashMap<>();
            // 提取列名（支持带表别名）
            condition.put("column", matcher.group(1).trim());
            // 提取LIKE参数（保留原始格式）
            condition.put("likeValue", matcher.group(2).trim());
            // 提取ESCAPE转义符（若无则返回null）
            condition.put("escape", matcher.group(3) != null ? matcher.group(3) : "");

            condition.put("all", matcher.group(0));
            results.add(condition);
        }
        return results;
    }

    public static void main(String[] args) {
        String sql = "SELECT * FROM products WHERE "
                + "name LIKE ? ESCAPE '\\' "   // 参数化占位符
                + "AND code LIKE '#{codeParam}' "  // 动态参数
                + "AND desc LIKE '%特殊_字符%' ESCAPE '$'";  // 直接字符串

        String sql1 = "SELECT * FROM products WHERE "
                + "description LIKE ? ESCAPE '!' OR "
                + "product.name LIKE ? ESCAPE '\\'"
                ;


        test(sql);
        System.out.println("==========================================================");
        test(sql1);
    }

    public static void test(String sql) {
        List<Map<String, String>> conditions = extractLikeConditions(sql);
        conditions.forEach(cond -> System.out.println("列名: " + cond.get("column") +
                        ", LIKE值: " + cond.get("likeValue") +
                        ", 转义符: " + (cond.get("escape").isEmpty() ? "无" : cond.get("escape")))
        );

        conditions.forEach(item -> {
            System.out.println(item.get("all"));
        });
    }

}

